/**
 * Copyright (C), 2015-2019, XXX有限公司
 * FileName: MailController
 * Author:   pc
 * Date:     2019/9/11 13:59
 * Description: 验证码：邮箱篇
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
package com.example.rabbitmqdemo.controller;

import com.example.rabbitmqdemo.annotation.MyLog;
import com.example.rabbitmqdemo.utils.IsMailAndPhoneUtil;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 〈功能：〉<br> 
 * 〈验证码：邮箱篇〉
 * @author liuhaoran
 * @create 2019/9/11 13:59
 * @since 1.0.0
 */
@Controller
@Configuration
public class MailController {
	@Autowired
	JavaMailSender javaMaulSender;
	@Autowired
	IsMailAndPhoneUtil isMailAndPhoneUtil;
	@Autowired
	private RedisTemplate redisTemplate;

	@ResponseBody
	@RequestMapping(value = "/sendmail", method = RequestMethod.GET)
	public String sendmail(@RequestParam(value = "userinfomail")String userinfomail) {
		ValueOperations<String, Map<String, String>> operations = redisTemplate.opsForValue();
		Map<String,String> map = new HashMap<String, String>();
		if(isMailAndPhoneUtil.isEmail(userinfomail)){
			// 随机生成8位数
			String codeNumber = RandomStringUtils.randomNumeric(4);
			map.put("codenumber",codeNumber);
			SimpleMailMessage message = new SimpleMailMessage();
			message.setFrom("384473780@qq.com");
			message.setTo(userinfomail); // 937875334@qq.com 测试邮箱
			message.setSubject("来自一封测试网");
			operations.set(userinfomail+"codenum", map, 180, TimeUnit.SECONDS); // seconds 单位秒
			message.setText("感谢你登录测试网,您的验证码为："+codeNumber+",感谢您的查看");
			try {
				javaMaulSender.send(message);
			}catch (Exception e){
				return "success";
			}
			return "success";
		} else {
			return "邮箱或者手机格式不正确";
		}
	}

}